/* =======================================================================
 * jQuery.Huitag.js v2.0 标签
 * http://www.h-ui.net/
 * Created & Modified by guojunhui
 * Date modified 2024.09.12
 * Copyright 2017-2024 郭俊辉 All rights reserved.
 * Licensed under MIT license.
 * http://opensource.org/licenses/MIT
 * ========================================================================*/
!function($) {
  $.fn.Huitag = function(options) {
    var defaults = {
      value: 'Hui前端框架,H-ui,辉哥',
      maxlength: 20,
      number: 5,
      tagsDefault: ["Html", "CSS", "JS"]
    };
    var settings = $.extend({}, defaults, options);
    var keyCodes = {
      Enter: 13,
      Enter2: 108,
      Spacebar: 32
    };

    this.each(function() {
      var $this = $(this);
      var $wrapper = $('<div class="hui-tag-wrapper"><div class="hui-tag-editor clearfix"></div><div class="hui-tag-input-wrapper"><input type="text" class="hui-input-text hui-tag-input" maxlength="' + settings.maxlength + '" value=""></div><div class="hui-tag-list"><div class="hui-tag-notag" style="display:none">暂无常用标签</div><div class="hui-tag-has"></div></div><input type="hidden" class="hui-tag-val" name="" value="' + settings.value + '"></div>');
      $this.append($wrapper);

      var $editor = $wrapper.find('.hui-tag-editor');
      var $input = $wrapper.find('.hui-tag-input');
      var $has = $wrapper.find('.hui-tag-has');
      var $val = $wrapper.find('.hui-tag-val');

      // 初始化默认标签
      var defaultValues = settings.value.split(',');
      $.each(defaultValues, function(index, tag) {
        addTag(tag, true);
      });

      // 添加标签图标
      $editor.prepend('<i class="hui-tag-icon hui-iconfont">&#xe64b;</i>');

      if (settings.tagsDefault) {
        $.each(settings.tagsDefault, function(index, tag) {
          $has.append('<span>' + tag + '</span>');
        });
        $has.find('span').on('click', function() {
          addTag($(this).text());
          $(this).remove();
        });
      }

      $input.on('keydown', function(e) {
        var evt = e || window.event;
        if ([keyCodes.Enter, keyCodes.Enter2, keyCodes.Spacebar].indexOf(evt.keyCode) !== -1) {
          e.preventDefault(); // 防止默认行为，如表单提交
          handleInput();
        }
      });

      $input.on('change', handleInput);

      $wrapper.on('click', '.hui-tag-token', function() {
        removeTag($(this));
      });

      function addTag(tag, isDefault) {
        if (!isDuplicate(tag)) {
          var $tagSpan = $('<span class="hui-tag-token">' + tag + '</span>');
          $editor.append($tagSpan);
          updateHiddenValue(tag, true);
          if (!isDefault) {
            $has.find('span').each(function() {
              if ($(this).text() === tag) {
                $(this).remove();
              }
            });
          }
        }
      }

      function removeTag($tag) {
        $tag.remove();
        updateHiddenValue($tag.text(), false);
        if ($editor.find('.hui-tag-token').length === 0) {
          $val.val('');
        } else {
          var tags = $editor.find('.hui-tag-token').map(function() { return $(this).text(); }).get();
          $val.val(tags.join(','));
        }
        $has.append('<span>' + $tag.text() + '</span>');
      }

      function handleInput() {
        var value = $.trim($input.val().replace(/\s+/g, ''));
        if (value) {
          addTag(value);
          $input.val('');
        }
      }

      function isDuplicate(tag) {
        var tags = $editor.find('.hui-tag-token').map(function() { return $(this).text(); }).get();
        return $.inArray(tag, tags) > -1;
      }

      function updateHiddenValue(tag, add) {
        var tags = $editor.find('.hui-tag-token').map(function() { return $(this).text(); }).get();
        var index = $.inArray(tag, tags);
        if (add && index === -1) {
          tags.push(tag);
        } else if (!add && index !== -1) {
          tags.splice(index, 1);
        }
        $val.val(tags.join(','));
      }
    });
  };
} (window.jQuery);
